package com.cgsd.heyu.http;


import android.content.Context;

import com.android.library.utils.LogUtils;
import com.android.library.utils.SystemUtil;
import com.cgsd.heyu.App;
import com.cgsd.heyu.common.Constants;

import io.reactivex.Observer;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;

/**
 * @author xiaoxing
 * Created by Administrator on 2018/3/25.
 */

public  abstract class BaseRxSubscribe<T> implements Observer<T> {
    private Disposable disposable;
    private Context context;
    private String errorMsg;

    public BaseRxSubscribe(Context context){
        this.context = context;
    }

    public BaseRxSubscribe(){
        this.context = context;
    }

    @Override
    public void onSubscribe(Disposable d) {
        disposable = new CompositeDisposable();
    }


    @Override
    public void onNext(T value) {
        if (value instanceof BaseResponse) {
            BaseResponse response = (BaseResponse) value;
            if (Constants.SUCCESS_CODE != response.getCode() ){
                onError(new ErrorMessage(response.getCode(),response.getError()));
            }else {
                onSuccess(value);
            }
        }else {
            onSuccess(value);
        }

    }


    @Override
    public void onError(Throwable e) {
        //错误信息打印
        LogUtils.e(LogUtils.DEFAULT_TAG,e.getMessage());
        ExceptionHandler.ResponseThrowableException responseThrowable;
        //接下来可以检查网络连接等操作
        if (!SystemUtil.isNetworkAvailable(App.getInstance())) {
            onError(new ErrorMessage(GlobalErrorMessage.ErrorMessage.ERROR_MESSAGE_1000));
        }else if (e instanceof AnalysisErrorException){
            //解析异常
            AnalysisErrorException analysisErrorException = (AnalysisErrorException) e;
            onError(new ErrorMessage(analysisErrorException.getCode(),analysisErrorException.getMessage(),analysisErrorException.getBody()));
        } else if(e instanceof Exception){
            //访问获得对应的Exception
            responseThrowable = ExceptionHandler.handleException(e);
            onError(new ErrorMessage(responseThrowable.code,responseThrowable.message));
        }else {
            //将Throwable 和 未知错误的status code返回
            responseThrowable = new ExceptionHandler.ResponseThrowableException(e,ExceptionHandler.Error.UNKNOWN);
            onError(new ErrorMessage(responseThrowable.code,responseThrowable.message));
        }
    }

    @Override
    public void onComplete() {

    }

    public abstract void onSuccess(T t);


    public abstract void onError(ErrorMessage error);

}
